package cn.niit.letuseatdemo.controller.store;

import cn.niit.letuseatdemo.entity.domain.Store;
import cn.niit.letuseatdemo.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:商家登录控制器
 * @Author: zhang_bowen
 * @CreateTime： 2022/11/30 20:38
 */
@Controller
public class StoreLoginController {

    @Autowired
    private StoreService storeService;
    /*
      * @Description:用于商家访问 /store/login 后在浏览器中显示登录页面
      * @Author: zhang_bowen
      * @CreateTime: 2022/11/30  20:59
 * @return: java.lang.String
      **/
    @GetMapping("/store/login")
    public String loginIndex(){

        return "/store/login";
    }

    /*
      * @Description: 接收商家登录请求，并验证账号、密码、验证码是否正确
      *              如果正确，则跳转至 /store/index
      *              如果错误，则跳转至 /store/login
      * @Author: zhang_bowen
      * @CreateTime: 2022/11/30  21:09
 * @return: java.lang.String
      **/
    @PostMapping("/store/login")
    public String login(String storePhone, String storePassword, String verifyCode, HttpServletRequest request){
        System.out.println("storePhone = " + storePhone + "storePassword = " + storePassword + "verifyCode = " + verifyCode);

        if(!StringUtils.hasLength(verifyCode)){
            request.setAttribute("errorMsg","验证码不能为空！");
            return "/store/login";
        }

        String kaptchaCode = request.getSession().getAttribute("verifyCode") + "";
        if(!verifyCode.equals(kaptchaCode)){
            request.setAttribute("errorMsg","验证码错误！");
            return "/store/login";
        }

        if(!StringUtils.hasLength(storePhone) || !StringUtils.hasLength(storePassword)){
            request.setAttribute("errorMsg","账号、密码不能为空！");
            return "/store/login";
        }

        /*
          * @Description: 验证账号密码是否正确：与数据库中的账号密码是否一致？
          * @Author: zhang_bowen
          * @CreateTime: 2022/11/30  21:29
 * @return: java.lang.String
          **/
        Store store = storeService.getStoreByStorePhoneStorePassword(storePhone,storePassword);
        if(null != store){
            if(store.getStoreRegisterState()==1){
                request.getSession().setAttribute("storeStoreId",store.getStoreId());
                request.getSession().setAttribute("store",store);
                //验证通过
                return "/store/index";
            }else {
                //账号或密码错误
                request.setAttribute("errorMsg","等待管理员审核，审核通过后即可登录");
                return "/store/login";
            }
        }else {
            //账号或密码错误
            request.setAttribute("errorMsg","账号或密码错误！");
            return "/store/login";
        }

    }
}